<?php
    /**
     * User zgh
     * Email 1803897171@qq.com
     * Date 2021/8/5
     **/

    namespace app\api\service;


    use app\common\exception\ServiceException;
    use app\common\model\NewsModel;

    class NewsService
    {
        public static function getList($params)
        {
            $pagination = filter_pagination(@$params['page'], @$params['limit']);
            $where = [];
            $data = [];
            if (isset($params['title']) && !empty($params['title'])) {
                $where[] = ["title", "like", "%" . $params['title'] . "%"];
            }
            if (isset($params['type']) && is_numeric($params['type'])) {
                $where[] = ["type", "=", $params['type']];
            }
            $where[] = ['status', '=', 1];
            $where[] = ['publish_time', '<=', current_datetime()];
            $query = NewsModel::field("id,type,title,brief,images,publish_time")->where($where)->order(["weight" => "desc", "publish_time" => "desc"]);
            $data['total'] = $query->count();
            $data['dataList'] = [];
            if ($data['total']) {
                $data['dataList'] = $query->limit($pagination['start'], $pagination['limit'])->select()->toArray();
                foreach ($data['dataList'] as &$data_row) {
                    $data_row['images'] = get_http_path($data_row['images']);
                }
            }
            return $data;
        }


        public static function getDetail($params)
        {
            $news_id = $params['id'] ? (int)$params['id'] : 0;
            $model = NewsModel::field("id,type,title,brief,images,publish_time,real_read_num,read_num")->where(["id" => $news_id, "status" => 1])->find();
            if (empty($model)) {
                throw new ServiceException("没找到相关资讯");
            }
            $model->real_read_num += 1;
            $model->read_num += 1;
            $model->save();
            $data_row = filter_params($model->toArray(), "real_read_num,update_time");
            $data_row['images'] = get_http_path($data_row['images']);
            return $data_row;
        }

        public static function share($params)
        {
            $news_id = $params['id'] ? (int)$params['id'] : 0;
            return NewsModel::where(["id" => $news_id])->inc("share_num,real_share_num")->update();
        }

    }
